﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;

namespace EnergyService_CSharp
{
    public class EnergyReading
    {
        public DateTime TimeStamp { get; private set; }
        public float Energy { get; private set; }
        public float Temperature { get; private set; }
        public bool IsValid { get; private set; }

        public EnergyReading(string readingData)
        {
            TimeStamp = DateTime.MinValue;
            Energy = float.NaN;
            Temperature = float.NaN;
            IsValid = false;

            try
            {
                // parse the xml based reading
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(readingData);

                XmlNode xNode = xDoc.SelectSingleNode("/msg/time");
                TimeStamp = System.Xml.XmlConvert.ToDateTime(xNode.InnerText);
                xNode = xDoc.SelectSingleNode("/msg/tmpr");
                if (null == xNode)
                {
                    // try the tmprF element instead
                    xNode = xDoc.SelectSingleNode("/msg/tmprF");
                }
                Temperature = System.Xml.XmlConvert.ToSingle(xNode.InnerText);
                xNode = xDoc.SelectSingleNode("/msg/ch1/watts");
                if ((null != xNode) && (string.Empty != xNode.InnerText))
                {
                    Energy = System.Xml.XmlConvert.ToInt32(xNode.InnerText);
                }

                xNode = xDoc.SelectSingleNode("/msg/ch2/watts");
                if ((null != xNode) && (string.Empty != xNode.InnerText))
                {
                    Energy += System.Xml.XmlConvert.ToInt32(xNode.InnerText);
                }

                xNode = xDoc.SelectSingleNode("/msg/ch3/watts");
                if ((null != xNode) && (string.Empty != xNode.InnerText))
                {
                    Energy += System.Xml.XmlConvert.ToInt32(xNode.InnerText);
                } 
                
                IsValid = true;
            }
            catch (Exception ex)
            {
                // invalid reading
                Debug.WriteLine("Error parsing xml data to create EnergyReading: " + ex.Message);
            }
        }

        public override string ToString()
        {
            return TimeStamp.ToLongTimeString() + " - " + Energy.ToString("N") + " Watts - " + Temperature.ToString("N") + " Degrees";
        }
    }
}
